package br.zeos.bean;

import br.zeos.ZDataSource;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import java.util.HashMap;
import javax.swing.AbstractButton;

public class zGroupButton extends javax.swing.ButtonGroup implements ActionListener {

    private ZDataSource origem = null;
    private String FieldName = "";

    public ZDataSource getDataSource() {
        return origem;
    }

    public void setDataSource(final ZDataSource origem) {
        this.origem = origem;
        this.origem.addUpdateListener(this);
        for (AbstractButton next : buttons) {
            next.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    updateData();
                }
            });
        }
    }

    private String getValue() {
        for (Enumeration<AbstractButton> buttons = this.getElements(); buttons.hasMoreElements();) {
            AbstractButton button = buttons.nextElement();
            if (button.isSelected()) {
                return button.getText();
            }
        }
        return "";
    }

    private void setValue(String v) {
        for (AbstractButton next : buttons) {
            next.setSelected(next.getText().equalsIgnoreCase(v));
        }

    }

    private void updateData() {
        //arrumar
        HashMap<String, String> linha = this.origem.getLine();
        String valorzinhoSelecionadopelomeuMOUSE = this.getValue();
        if(valorzinhoSelecionadopelomeuMOUSE.isEmpty()){
            return;
        }
        linha.put(FieldName.toUpperCase(), valorzinhoSelecionadopelomeuMOUSE);
        this.origem.setLinha(linha);
    }

    public String getFieldName() {
        return FieldName;
    }

    public void setFieldName(String FieldName) {
        this.FieldName = FieldName;
        updateData();
        this.actionPerformed(null);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        this.setValue(origem.getLine().get(this.getFieldName().toUpperCase()));
    }

}
